<template>
    <!-- 保持模板结构不变 -->
    <div class="min-h-screen bg-gradient-to-br from-pink-100 to-purple-100">
        <div class="container mx-auto px-4 py-8 max-w-4xl">
            <div class="bg-white rounded-2xl shadow-2xl overflow-hidden">
                <!-- Header -->
                <div class="bg-gradient-to-r from-pink-400 to-purple-500 p-6 relative">
                    <div class="absolute top-1 right-1 flex items-center justify-center gap-2">
                        <a class="AppHeader-logo ml-1" href="http://www.git.com.cn/index.html">
                            <img src="http://www.git.com.cn/templates/cn/images/logo.png"/>
                        </a>
                    </div>

                    <h1 class="text-3xl md:text-4xl font-bold text-white text-center">
                        <a href="http://www.git.com.cn/" target="_blank" class="hover:text-gray-100 transition-colors">
                            Git Chat
                        </a>
                    </h1>
                    <p class="text-white text-center mt-2 opacity-90">钢是在烈火里燃烧、高度冷却中炼成的，因此它很坚固。</p>
                </div>

                <!-- Chat Container -->
                <div
                    ref="chatBox"
                    class="h-[60vh] overflow-y-auto p-6 bg-gray-50 scroll-smooth"
                    @scroll="handleScroll"
                >
                    <TransitionGroup
                        name="message"
                        enter-active-class="transition-all duration-300 ease-out"
                        enter-from-class="opacity-0 transform translate-y-4"
                        enter-to-class="opacity-100 transform translate-y-0"
                    >
                        <ChatMessage
                            v-for="(msg, index) in messages"
                            :key="index"
                            :message="msg"
                            :is-last="index === messages.length - 1"
                        />
                    </TransitionGroup>
                    <div v-if="isTyping" class="flex items-center space-x-2 p-4">
                        <div class="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    </div>
                </div>

                <!-- Input Area -->
                <MessageInput
                    v-model="userMessage"
                    @send="sendMessage"
                    :disabled="isTyping"
                    @keydown.enter.prevent="handleEnter"
                />

                <!-- Footer -->
                <footer class="bg-gray-50 p-4 border-t border-gray-200">
                    <div class="flex flex-col items-center space-y-2">
                        <p class="text-gray-600 text-sm hover:text-gray-800 transition-colors">
                            <a href="https://bailian.console.aliyun.com" target="_blank">
                                版权所有 © 高伟达 京ICP备15004154号-1 由阿里云千问大模型支持
                            </a>
                        </p>
                    </div>
                </footer>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import ChatMessage from './ChatMessage.vue'
import MessageInput from './MessageInput.vue'

export default {
    name: 'ChatView',
    components: { ChatMessage, MessageInput },

    setup() {
        const chatBox = ref(null)
        const userMessage = ref('')
        const messages = ref([])
        const isTyping = ref(false)
        const showScrollButton = ref(false)

        // 滚动处理函数
        const scrollToBottom = async () => {
            await nextTick()
            if (chatBox.value) {
                chatBox.value.scrollTop = chatBox.value.scrollHeight
            }
        }

        const handleScroll = () => {
            if (!chatBox.value) return
            const { scrollTop, scrollHeight, clientHeight } = chatBox.value
            showScrollButton.value = scrollHeight - scrollTop - clientHeight > 100
        }

        const scrollToBottomSmooth = () => {
            if (chatBox.value) {
                chatBox.value.scrollTo({
                    top: chatBox.value.scrollHeight,
                    behavior: 'smooth'
                })
            }
        }

        // 消息处理
        const handleEnter = (e) => {
            if (!e.shiftKey) {
                sendMessage()
            }
        }

        const sendMessage = async () => {
            const message = userMessage.value.trim()
            if (!message || isTyping.value) return

            // 添加用户消息
            messages.value.push(reactive({
                text: message,
                sender: 'user',
                timestamp: new Date().toISOString()
            }))

            userMessage.value = ''
            isTyping.value = true
            await scrollToBottom()

            let botMessageIndex
            try {
                const response = await fetch(
                    `/api/ai/stream?prompt=${encodeURIComponent(message)}`,
                    { method: 'GET' }
                )

                if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`)

                // 初始化机器人消息
                messages.value.push(reactive({
                    text: '',
                    sender: 'bot',
                    timestamp: new Date().toISOString()
                }))
                botMessageIndex = messages.value.length - 1

                const reader = response.body.getReader()
                const decoder = new TextDecoder('utf-8')
                let buffer = ''
                let fullMessage = ''

                try {
                    while (true) {
                        const { done, value } = await reader.read()
                        if (done) break

                        buffer += decoder.decode(value, { stream: true })

                        // 解析事件流
                        let eventEndIndex
                        while ((eventEndIndex = buffer.indexOf('\n\n')) !== -1) {
                            const eventData = buffer.slice(0, eventEndIndex)
                            buffer = buffer.slice(eventEndIndex + 2)

                            const lines = eventData.split('\n')
                            let eventType = 'ai-message'
                            let content = ''

                            for (const line of lines) {
                                if (line.startsWith('event:')) {
                                    eventType = line.replace('event:', '').trim()
                                } else if (line.startsWith('data:')) {
                                    content += line.replace('data:', '').trim()
                                }
                            }

                            if (eventType === 'ai-message') {
                                fullMessage += content
                            }
                        }

                        // 更新完整消息内容
                        if (fullMessage) {
                            messages.value[botMessageIndex].text = fullMessage
                            await nextTick()
                            await scrollToBottom()
                        }
                    }

                    // 处理最后剩余数据
                    if (buffer) {
                        const lines = buffer.split('\n')
                        for (const line of lines) {
                            if (line.startsWith('data:')) {
                                fullMessage += line.replace('data:', '').trim()
                            }
                        }
                        messages.value[botMessageIndex].text = fullMessage
                        await nextTick()
                        await scrollToBottom()
                    }
                } finally {
                    reader.releaseLock()
                }
            } catch (error) {
                console.error('请求失败:', error)
                const errorMessage = error.message.includes('Failed to fetch') 
                    ? '网络连接异常，请检查网络后重试' 
                    : '服务暂时不可用，请稍后再试'

                if (typeof botMessageIndex !== 'undefined') {
                    messages.value[botMessageIndex].text = errorMessage
                } else {
                    messages.value.push(reactive({
                        text: errorMessage,
                        sender: 'bot',
                        timestamp: new Date().toISOString()
                    }))
                }
            } finally {
                isTyping.value = false
                await scrollToBottom()
            }
        }

        // 初始化欢迎消息
        onMounted(() => {
            messages.value.push(reactive({
                text: '你好，我是高伟达的智能助手，请问有什么可以帮您？',
                sender: 'bot',
                timestamp: new Date().toISOString()
            }))
        })

        return {
            chatBox,
            userMessage,
            messages,
            isTyping,
            showScrollButton,
            sendMessage,
            handleScroll,
            scrollToBottomSmooth,
            handleEnter
        }
    }
}
</script>

<style scoped>
.typing-indicator {
    display: flex;
    align-items: center;
    gap: 4px;
}

.typing-indicator span {
    width: 8px;
    height: 8px;
    background-color: #33e5e5;
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1.0); }
}

.scroll-smooth {
    scroll-behavior: smooth;
}
</style>